// 用户管理界面
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:im_app/im/page/view/LoadingView.dart';
import 'package:im_app/im/page/view/component/cell/UserItemView.dart';
import 'package:provider/provider.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

import 'bloc/UserListCubit.dart';

/// 用户按照首字母分组展示
class UserPage extends StatefulWidget {

  const UserPage({super.key});

  @override
  State<StatefulWidget> createState() {
     return _listState();
  }
}

class _listState extends State<UserPage> {

  late AutoScrollController _autoScrollController;

  @override
  void initState() {
    super.initState();
    _autoScrollController = AutoScrollController(viewportBoundaryGetter: () =>Rect.fromLTRB(0, 0, 0, MediaQuery.of(context)
        .padding.bottom), axis: Axis.vertical);
  }

  @override
  Widget build(BuildContext context) {
    final state = context.watch<UserListCubit>().state;
    return LoadingView(state: state.state, child: _buildListView(context));
  }

  Widget _buildListView(BuildContext context) {
    final state = context.watch<UserListCubit>().state;
    return Stack(
      children: [
        // Expanded(child: _buildPullView2()),
        _buildPullView(context),
        Positioned(right: 10, child: Center(
          child: Column(
              children: state.letters.asMap().map<int, Widget>((index, letter) =>
                  MapEntry(index, GestureDetector(
                    child: _buildLetter(letter),
                    onTap: ()=>_jumpeToUser(state.letters, state.letterSizeMap, letter),)
                  )
              ).values.toList()
          ),
        ),)
      ],
    );
  }

  Widget _buildPullView(BuildContext context) {
    return EasyRefresh(
      // controller: _easyRefreshController,
      header: const ClassicHeader(processedText: "加载数据成功！", dragText: "下拉会加载数据", armedText: "放松加载数据",
          processingText: "正在加载数据！", readyText: "加载数据完数据"),
      footer: const ClassicFooter(),
      onRefresh: () async {
        await context.read<UserListCubit>().loadData();
      },
      onLoad: () async {
        try {
          return await context.read<UserListCubit>().loadMoreData();
        } catch(error, stracktrace) {
          print('error==');
        }
      },
      child: _buildUserList(context)
    );
  }

  /// 用户列表
  Widget _buildUserList(BuildContext context){
    final state = context.watch<UserListCubit>().state;
    return ListView.builder(
      controller: _autoScrollController,
      scrollDirection: Axis.vertical,
      itemCount: state.users.length,
      // shrinkWrap: true,
      cacheExtent: 5,
      itemBuilder: (context, index) {
        var preUser = index > 0 ? state.users.elementAt(index-1) : null;
        return AutoScrollTag(
            key: ValueKey(index),
            controller: _autoScrollController,
            index: index,
            child: UserItemView(state.users.elementAt(index), preUser)
        );
      },
      // separatorBuilder: (context, index) {
      //   return Padding(padding: EdgeInsets.only(top: 5, bottom: 5), child: ListSeparator(),);
      // },
    );
  }

  Widget _buildLetter(String letter) {
    return Padding(padding: const EdgeInsets.only(left: 5, right: 10, top: 2, bottom: 2), child:
      Container(width: 20,
        decoration: const ShapeDecoration(
          shape: CircleBorder(),
          color: Colors.black12, // 圆点的颜色
        ),
        child: Center(child: Text(letter, style: const TextStyle(color: Colors.black87,),),),
      ),

    );
  }

  /// 调整首字母处
  void _jumpeToUser(List<String> letters, Map<String, int> letterSizeMap, String letter) async {
    var size = 0;
    print('Current letter0: $letter');
    for(var i=0; i<letters.length;i++){
      if (letters[i] == letter) {
        break;
      }
      size += letterSizeMap[letters[i]]??0;
    }
    print('Current letter0: $letter, $size');
    await _autoScrollController.scrollToIndex(size, preferPosition: AutoScrollPosition.begin);
    _autoScrollController.highlight(size);
  }

  @override
  void dispose() {
    super.dispose();
    this._autoScrollController.dispose();
  }
}